package tcm.com.gistone.controller;

import net.sf.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tcm.com.gistone.database.config.GetBySqlMapper;
import tcm.com.gistone.database.entity.Bookinfo;
import tcm.com.gistone.database.entity.Special;
import tcm.com.gistone.database.mapper.BookinfoMapper;
import tcm.com.gistone.database.mapper.SpecialMapper;
import tcm.com.gistone.util.ClientUtil;
import tcm.com.gistone.util.ConfigUtil;
import tcm.com.gistone.util.EdatResult;
import tcm.com.gistone.util.FileUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author:renqiang
 * @Param:
 * @Description:
 * @Date:14:48 2017/8/11
 */
@RestController
@RequestMapping( "database" )
@Transactional
public class DatebaseController {
    private final static org.slf4j.Logger logger = LoggerFactory.getLogger(ClientUtil.class);
    @Autowired
    private SpecialMapper sm;
    @Autowired
    private BookinfoMapper bm;
    @Autowired
    private GetBySqlMapper gm;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    @Autowired
    private ConfigUtil configUtil;

    /*更新后台表数据到前台表，将数据同步到待_copy的表，供前台查询使用*/
    @RequestMapping( value = "copy", method = RequestMethod.POST )
    public EdatResult swicth(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Date now;
        String hehe = "";
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            long specialId = data.getLong("specialId");
            now = new Date();
            hehe = dateFormat.format(now);
            List<Bookinfo> list = bm.selectAvai();
            if (list.size() > 0) {
                return EdatResult.build(1, "存在正在构建的文献，重新构建失败");
            }
            /*清空日志文件信息*/
            FileUtil.clearInfoForFile(configUtil.getLogUrl());
            /*写入日志文件*/
            FileUtil.writeToTxt(configUtil.getLogUrl(), " 开始更新");
            if (specialId == 1) {
                copy1();
            } else if (specialId == 2) {
                copy2();
            } else if (specialId == 3) {
                copy3();
            } else if (specialId == 0) {
                copy();
            }
            return EdatResult.build(0, "success");
        } catch (Exception e) {
            e.printStackTrace();
            now = new Date();
            hehe = dateFormat.format(now);
            FileUtil.writeToTxt(configUtil.getLogUrl(), hehe + " 更新失败");
            response.getWriter().write("{\"status\":\"1\",\"msg\":\"更新失败\",\"data\":\"\"}");
            throw e;
        }
    }

    /*更新草本专题统计数据*/
    public void copy1() {
        String hehe = "";
        long specialId = 1;
        Special special = sm.selectByPrimaryKey(specialId);
        logger.info("开始更新" + special.getSpecialName() + "专题知识构建数据");
        Date now = new Date();
        hehe = dateFormat.format(now);
        FileUtil.writeToTxt(configUtil.getLogUrl(), " 开始更新" + special.getSpecialName() + "专题知识构建数据");
        long t1 = System.currentTimeMillis();
        /*清空置信度表*/
        String sql1 = "truncate table tb_confidence_copy1";
        /*删除索引*/
        String sql11 = "DROP INDEX `wa` ON tb_confidence_copy1";
        /*添加索引*/
        String sql12 = "CREATE INDEX `wa` ON tb_confidence_copy1 (`word_id`,`ano_word_id`)";
        /*复制置信度数据*/
        String sql2 = "insert into tb_confidence_copy1 select * from tb_confidence1";
        /*删除段落主题词数据*/
        String sql3 = "delete from tb_ws_relation_copy where book_id in  (SELECT book_id from tb_bookinfo where special_id = 1 ) ";
        /*复制段落主题词数据到tb_ws_relation_copy*/
        String sql4 = "insert into tb_ws_relation_copy (select T1.* from tb_ws_relation T1 where  EXISTS (SELECT 1 from tb_bookinfo T2 where T2.special_id = 1 and T1.book_id = T2.book_id ))";
        /*删除主题词间数据*/
        String sql5 = "delete from tb_words_relation_copy  where book_id in (SELECT book_id from tb_bookinfo where special_id = 1 ) ";
         /*复制主题词间数据*/
        String sql6 = "insert into tb_words_relation_copy (select T1.* from tb_words_relation T1 where EXISTS (SELECT 1 from tb_bookinfo T2 where T2.special_id = 1 and T1.book_id = T2.book_id))";

        gm.delete(sql3);
        gm.insert(sql4);

        gm.delete(sql5);
        gm.insert(sql6);
        /*复制置信度表*/
        gm.delete(sql1);//删除旧数据
        gm.delete(sql11);//删除索引
        gm.insert(sql2);//复制数据
        gm.insert(sql12);//添加索引
        long t2 = System.currentTimeMillis();
        logger.info("更新" + special.getSpecialName() + "专题知识构建完成，耗时：" + (t2 - t1) / 1000 + "s");
        now = new Date();
        hehe = dateFormat.format(now);
        FileUtil.writeToTxt(configUtil.getLogUrl(), " 更新" + special.getSpecialName() + "专题知识构建数据完成，耗时：" + (t2 - t1) / 1000 + "s");
    }

    /*更新养生专题统计数据*/
    public void copy2() {
        Date now;
        String hehe = "";
        long specialId = 2;
        Special special = sm.selectByPrimaryKey(specialId);
        logger.info("开始更新" + special.getSpecialName() + "专题知识构建数据");
        now = new Date();
        hehe = dateFormat.format(now);
        FileUtil.writeToTxt(configUtil.getLogUrl(), " 开始更新" + special.getSpecialName() + "专题知识构建数据");
        long t1 = System.currentTimeMillis();
        String sql1 = "truncate table tb_confidence_copy2";
        String sql2 = "insert into tb_confidence_copy2 select * from tb_confidence2";
        String sql3 = "delete from tb_ws_relation_copy where book_id in  (SELECT book_id from tb_bookinfo where special_id = 2 ) ";
        String sql4 = "insert into tb_ws_relation_copy (select T1.* from tb_ws_relation T1 where  EXISTS (SELECT 1 from tb_bookinfo T2 where T2.special_id = 2 and T1.book_id = T2.book_id ))";
        String sql5 = "delete from tb_words_relation_copy  where book_id in (SELECT book_id from tb_bookinfo where special_id = 2 ) ";
        String sql6 = "insert into tb_words_relation_copy (select T1.* from tb_words_relation T1 where EXISTS (SELECT 1 from tb_bookinfo T2 where T2.special_id = 2 and T1.book_id = T2.book_id))";
        gm.delete(sql5);
        gm.insert(sql6);
        gm.delete(sql1);
        gm.insert(sql2);
        gm.delete(sql3);
        gm.insert(sql4);
        long t2 = System.currentTimeMillis();
        logger.info("更新" + special.getSpecialName() + "专题知识构建数据完成，耗时：" + (t2 - t1) / 1000 + "s");
        now = new Date();
        hehe = dateFormat.format(now);
        FileUtil.writeToTxt(configUtil.getLogUrl(), " 更新" + special.getSpecialName() + "专题知识构建数据完成，耗时：" + (t2 - t1) / 1000 + "s");
    }

    /*更新温病专题统计数据*/
    public void copy3() {
        Date now;
        String hehe = "";
        long specialId = 3;
        Special special = sm.selectByPrimaryKey(specialId);
        logger.info("开始更新" + special.getSpecialName() + "专题知识构建数据");
        now = new Date();
        hehe = dateFormat.format(now);
        FileUtil.writeToTxt(configUtil.getLogUrl(), " 开始更新" + special.getSpecialName() + "专题知识构建数据");
        long t1 = System.currentTimeMillis();
        String sql1 = "truncate table tb_confidence_copy3";
        String sql2 = "insert into tb_confidence_copy3 select * from tb_confidence3";
        String sql3 = "delete from tb_ws_relation_copy where book_id in  (SELECT book_id from tb_bookinfo where special_id = 3 ) ";
        String sql4 = "insert into tb_ws_relation_copy (select T1.* from tb_ws_relation T1 where  EXISTS (SELECT 1 from tb_bookinfo T2 where T2.special_id = 3 and T1.book_id = T2.book_id ))";
        String sql5 = "delete from tb_words_relation_copy  where book_id in (SELECT book_id from tb_bookinfo where special_id = 3 ) ";
        String sql6 = "insert into tb_words_relation_copy (select T1.* from tb_words_relation T1 where EXISTS (SELECT 1 from tb_bookinfo T2 where T2.special_id = 3 and T1.book_id = T2.book_id))";
        gm.delete(sql5);
        gm.insert(sql6);
        gm.delete(sql1);
        gm.insert(sql2);
        gm.delete(sql3);
        gm.insert(sql4);
        long t2 = System.currentTimeMillis();
        logger.info("更新" + special.getSpecialName() + "专题知识构建数据完成，耗时：" + (t2 - t1) / 1000 + "s");
        now = new Date();
        hehe = dateFormat.format(now);
        FileUtil.writeToTxt(configUtil.getLogUrl(), " 更新" + special.getSpecialName() + "专题知识构建数据完成，耗时：" + (t2 - t1) / 1000 + "s");
    }

    /*更新全库统计数据*/
    public void copy() {
        logger.info("开始更新全库知识构建数据");
        long t1 = System.currentTimeMillis();
        copy1();
        copy2();
        copy3();
        long t2 = System.currentTimeMillis();
        logger.info("更新全库知识构建数据完成，耗时：" + (t2 - t1) / 1000 + "s");
    }

}
